import json
from datetime import datetime
from django.shortcuts import render
from django.http import JsonResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.views.decorators.clickjacking import xframe_options_exempt
from django.db.models import Sum
from .models import InAndOutRecord, Supply
from common.TimeHandler import DateTimeHandler


# 物料出入库视图
# Create your views here.
@xframe_options_exempt
def index(request):
    return render(request, "record/index.html")


def record_list(request):
    result = {"status": 1, "msg": "操作失败！"}
    data = request.GET
    try:
        page = data.get("page", 1)
        limit = data.get("limit", 5)
        search = data.get("search")
        record_type = data.get("record_type")

        records = InAndOutRecord.objects.filter(is_delete=0)
        if search and search != "":
            records = records.filter(supply__name__icontains=search)
        if record_type and int(record_type) in [1, 2]:
            records = records.filter(order_type=int(record_type))

        record_count = records.count()
        paginator = Paginator(records.order_by("-create_time"), limit)     # 每页多少条数据
        try:
            records = paginator.page(page)        # 返回 page（页数）的数据
        except PageNotAnInteger:
            records = paginator.page(1)           # 第一页
        except EmptyPage:
            records = paginator.page(paginator.num_pages)  # 最后一页

        data_list = []
        for i in range(len(records)):
            data_list.append({
                "No": i+1,
                "id": records[i].id,
                "order_no": records[i].order_no,
                "order_type": records[i].order_type,
                "supply_name": records[i].supply.name,
                "number": records[i].number,
                "cur_number": records[i].supply.number if records[i].cur_number is None and records[i].status == 0 else records[i].cur_number,
                "last_number": records[i].last_number,
                "img_url": records[i].img_url,
                "status": records[i].status,
                "operator": records[i].operator,
                "create_time": str(records[i].create_time).split(".")[0],
                "confirm_user": records[i].confirm_user,
                "confirm_time": records[i].confirm_time.strftime("%Y-%m-%d %H:%M:%S") if records[i].confirm_time else None,
                "remark": records[i].remark,
            })
            print(records[i].confirm_time)

        result["data"] = data_list
        result["data_count"] = record_count
        result["status"] = 0    # layui parseData status=0 才认为是成功
        result["msg"] = "出入库列表查询成功！"
    except Exception as e:
        print(e)
    return JsonResponse(result)


@xframe_options_exempt
def record_add(request, order_type=0):
    order_type = int(order_type)        # 0-未知，1-入库，2-出库
    if request.method == "POST":
        result = {"status": 0, "msg": "操作失败！"}
        data = json.loads(request.body)
        try:
            print(data)
            supply_id = data.get("supply_id")
            number = int(data.get("number", 0))
            img_url = data.get("img_url")
            remark = data.get("remark")

            order_no = "202007141435551234"
            operator = "mason"
            if order_type not in [1, 2]:
                result["msg"] = "操作类型不正确！"
                return JsonResponse(result)
            sp_exist = Supply.objects.filter(id=int(supply_id), is_delete=0).first()
            if not sp_exist:
                result["msg"] = "该物料不存在！"
                return JsonResponse(result)

            new_record = InAndOutRecord.objects.create(order_no=order_no, order_type=order_type, supply_id=int(supply_id),
                                                       number=number, img_url=img_url, remark=remark, operator=operator)
            new_record.save()
            result["status"] = 1
            result["msg"] = "物料入库单提交成功！" if order_type == 1 else "物料出库单提交成功！"
        except Exception as e:
            print(e)
        return JsonResponse(result)
    else:
        supplies = Supply.objects.filter(is_delete=0).order_by("-create_time").all()
        if order_type == 1:
            html_ = "record/add-in.html"
        else:
            html_ = "record/add-out.html"
        return render(request, html_, {"supplies": supplies})


@xframe_options_exempt
def record_verify(request):
    result = {"status": 0, "msg": "操作失败！"}
    if request.method == "POST":
        data = json.loads(request.body)
        try:
            print(data)
            record_id = data.get("record_id")
            record_status = int(data.get("record_status", 0))   # 0-待确认，1-确认，2-取消

            if record_status not in [1, 2]:
                result["msg"] = "操作类型不正确！"
                return JsonResponse(result)
            record = InAndOutRecord.objects.filter(id=int(record_id)).first()
            if not record:
                result["msg"] = "记录单不存在！"
                return JsonResponse(result)
            if record.status != 0:
                result["msg"] = "该出入库单已操作，请勿重复操作！"
                return JsonResponse(result)
            supply = Supply.objects.filter(id=record.supply_id, is_delete=0).first()
            if not supply:
                result["msg"] = "该出入库单对应的物料不存在！"
                return JsonResponse(result)

            confirm_user = "mason"
            if record_status == 1:
                sp_number = supply.number
                cur_number, last_number = 0, 0
                # 0-未知，1-入库，2-出库
                if record.order_type == 1:
                    last_number = sp_number
                    cur_number = last_number + record.number
                elif record.order_type == 2:
                    last_number = sp_number
                    if last_number < record.number:
                        result["msg"] = "该物料库存不足，无法操作！"
                        return JsonResponse(result)
                    cur_number = last_number - record.number
                record.cur_number = cur_number
                record.last_number = last_number
                supply.number = cur_number
                supply.save()

            record.status = record_status
            record.confirm_time = datetime.now()
            record.confirm_user = confirm_user
            record.save()
            result["status"] = 1
            result["msg"] = "出入库确认成功！" if record_status == 1 else "出入库取消成功！"
        except Exception as e:
            print(e)
    return JsonResponse(result)


@xframe_options_exempt
def record_edit(request, rc_id):
    if request.method == "POST":
        result = {"status": 0, "msg": "操作失败！"}
        data = json.loads(request.body)
        try:
            print(data)
            supply_id = int(data.get("supply_id"))
            number = int(data.get("number", 0))
            img_url = data.get("img_url")
            remark = data.get("remark")

            record = InAndOutRecord.objects.filter(id=int(rc_id), is_delete=0).first()
            if not record:
                result["msg"] = "请确认出入库单是否正确！"
                return JsonResponse(result)
            if record.status != 0:
                result["msg"] = "该出入库单已操作，无法更改！"
                return JsonResponse(result)
            if record.supply_id != supply_id:
                sp_exist = Supply.objects.filter(id=supply_id, is_delete=0).first()
                if not sp_exist:
                    result["msg"] = "该物料不存在！"
                    return JsonResponse(result)
                record.supply_id = supply_id
            if record.number != number:
                record.number = number
            if record.img_url != img_url:
                record.img_url = img_url
            if record.remark != remark:
                record.remark = remark
            record.save()
            result["status"] = 1
            result["msg"] = "出入库单信息更新成功!"
        except Exception as e:
            print(e)
        return JsonResponse(result)
    else:
        record = InAndOutRecord.objects.filter(id=int(rc_id), is_delete=0).first()
        supplies = Supply.objects.filter(is_delete=0).order_by("-create_time").all()
        return render(request, "record/edit.html", {'record': record, "supplies": supplies})


def record_del(request, rc_id):
    result = {"status": 0, "msg": "操作失败！"}
    if request.method == "DELETE":
        try:
            record = InAndOutRecord.objects.filter(id=int(rc_id), is_delete=0).first()
            if not record:
                result["msg"] = "请确认出入库单是否正确！"
                return JsonResponse(result)
            if record.status != 0:
                result["msg"] = "该出入库单已操作，无法删除！"
                return JsonResponse(result)
            record.is_delete = 1
            record.save()
            result["status"] = 1
            result["msg"] = "出入库单删除成功!"
        except Exception as e:
            print(e)
    return JsonResponse(result)


# 出入库数据统计
def in_out_statistics(request):
    result = {"status": 0, "msg": "查询失败！"}
    try:
        records = InAndOutRecord.objects.filter(status=1)

        # 当前总库存
        supply_count = Supply.objects.filter(is_delete=0).aggregate(Sum("number"))
        # 累计入库
        all_in_count = records.filter(order_type=1).aggregate(Sum("number"))
        # 累计出库
        all_out_count = records.filter(order_type=2).aggregate(Sum("number"))
        day_start, day_end = DateTimeHandler().day_start_end()
        print(day_start, day_end)
        # 今日入库
        today_in = records.filter(order_type=1, confirm_time__range=(day_start, day_end)).aggregate(Sum("number"))
        # 今日出库
        today_out = records.filter(order_type=2, confirm_time__range=(day_start, day_end)).aggregate(Sum("number"))

        # 本月出入库
        start, end = DateTimeHandler().month_start_end()
        cur_month_over_dates = DateTimeHandler().times_range_by_day(start, end)
        cur_records = records.filter(confirm_time__range=("%s 00:00:00" % start, "%s 23:59:59" % end)).order_by("create_time").all()
        # 上月出入库
        start, end = DateTimeHandler().month_start_end(DateTimeHandler().get_last_month())
        last_month_over_dates = DateTimeHandler().times_range_by_day(start, end)
        last_records = records.filter(confirm_time__range=("%s 00:00:00" % start, "%s 23:59:59" % end)).order_by("create_time").all()

        cur_data, last_data = [], []
        for t in cur_month_over_dates:
            arr = {
                "time": t,
                "in": 0,
                "out": 0,
            }
            for row in cur_records:
                if str(row.confirm_time).split(" ")[0] == t and row.order_type == 1:
                    arr["in"] += row.number
                elif str(row.confirm_time).split(" ")[0] == t and row.order_type == 2:
                    arr["out"] += row.number
            cur_data.append(arr)
        for t in last_month_over_dates:
            arr = {
                "time": t,
                "in": 0,
                "out": 0,
            }
            for row in last_records:
                if str(row.confirm_time).split(" ")[0] == t and row.order_type == 1:
                    arr["in"] += row.number
                elif str(row.confirm_time).split(" ")[0] == t and row.order_type == 2:
                    arr["out"] += row.number
            last_data.append(arr)

        data = {
            "statistics": {
                "supply_count": supply_count["number__sum"] if supply_count["number__sum"] else 0,
                "all_in_count": all_in_count["number__sum"] if all_in_count["number__sum"] else 0,
                "all_out_count": all_out_count["number__sum"] if all_out_count["number__sum"] else 0,
                "today_in": today_in["number__sum"] if today_in["number__sum"] else 0,
                "today_out": today_out["number__sum"] if today_out["number__sum"] else 0,
            },
            "cur_data": {
                "dates": [i["time"] for i in cur_data],
                "supply_in": [i["in"] for i in cur_data],
                "supply_out": [i["out"] for i in cur_data],
            },
            "last_data": {
                "dates": [i["time"] for i in last_data],
                "supply_in": [i["in"] for i in last_data],
                "supply_out": [i["out"] for i in last_data],
            },
        }
        result["status"] = 1
        result["msg"] = "出入库统计查询成功!"
        result["data"] = data
    except Exception as e:
        print(e)
    return JsonResponse(result)



